package com.dqyt.khjc.service;

import com.dqyt.common.check.CheckTool;
import com.dqyt.common.constant.AuthorityID;
import com.dqyt.common.constant.Opt;
import com.dqyt.common.utils.RegularUtil;
import com.dqyt.common.utils.UserInfoUtil;
import com.dqyt.khjc.bean.*;
import com.dqyt.khjc.config.Config;
import com.dqyt.khjc.controller.SmsController;
import com.dqyt.khjc.mapper.*;
import com.dqyt.khjc.mongo.WorkDao;
import com.dqyt.khjc.swicth.SwitchConfig;
import com.dqyt.khjc.utils.IpUtil;
import com.dqyt.khjc.utils.PNGUtil;
import com.dqyt.khjc.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 个人信息管理
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;


    @Autowired
    private HistoryMapper historyMapper;


    @Autowired
    private BSmsMapper mSmsMapper;

    @Autowired
    private SealMapper sealMapper;

    @Autowired
    private WorkDao mWorkDao;

    /**
     * 更具Id查询用户信息
     *
     * @param request
     * @return
     */
    public ResultMsg getUserById(HttpServletRequest request) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.GRXXGL_GRXXSZ)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }
            User nUser = userMapper.getUserByIdOrS(user.getUserId());
            nUser.setPassword("");

            //查询 所有角色信息
            List<Role> roles = roleMapper.getRoleListToName();


            UserByRoleBean userByRoleBean = new UserByRoleBean();
            userByRoleBean.setUser(nUser);
            userByRoleBean.setRoleList(roles);

            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("成功");
            ret.setData(userByRoleBean);

        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 修改个人信息
     *
     * @param request
     * @param avatar
     * @param userName
     * @param account
     * @param seal
     * @return
     */
    @Transactional
    public ResultMsg updateUser(HttpServletRequest request, String avatar, String userName, String account,String phone, String seal) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.GRXXGL_GRXXSZ)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            User nUser = userMapper.getUserByIdOrS(user.getUserId());


            if(!nUser.getAccount().equals(account)){
                //判断账号重复
                long mcount1 =   userMapper.getUserByCount(account);
                if(mcount1>0){
                    ret.setCode(ResultMsg.ERROR);
                    ret.setMsg("该账号已经被注册");
                    return ret;
                }
            }

            if(!nUser.getPhone().equals(phone)){
                //判断账号重复
                long mcount2 =  userMapper.getUserByPhoneCun(phone);
                if(mcount2>0){
                    ret.setCode(ResultMsg.ERROR);
                    ret.setMsg("该手机号已经被注册");
                    return ret;
                }
            }


            if (!"".equals(avatar)) {
                nUser.setAvatar(avatar);
            }


            int updateRes = 0;
            nUser.setPhone(phone);
            //如果当前印章是空的  或者  印章的地址和数据库一致  证明没有修改过印章
            if ("".equals(seal) || nUser.equals(seal)) {
                nUser.setUserName(userName);
                nUser.setAccount(account);
                nUser.setSealId(nUser.getSealId());
                updateRes = userMapper.updateUserById(nUser);
            } else {  //印章地址已经更改
                SealBean sealBean = new SealBean();
                sealBean.setUserId(user.getUserId());
                sealBean.setSealUrl(seal);
                long mmtime = TimeUtil.currentTimeMillis();
                sealBean.setAddTime(mmtime);
                sealBean.setSealUrlWmk("");
                sealBean.setAddUser(String.valueOf(user.getUserId()));
                sealBean.setUpdateTime(mmtime);
                sealBean.setUpdateUser(String.valueOf(user.getUserId()));

                //添加一个新的印章
                int mmres = sealMapper.addSeal(sealBean);
                if (mmres > 0) {
                    nUser.setUserName(userName);
                    nUser.setAccount(account);
                    nUser.setSealId(sealBean.getSealId());
                    updateRes = userMapper.updateUserById(nUser);

                    //如果操作日志的开关已经打开
                    if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                        //添加新增印章的操作记录
                        String ip = IpUtil.getIpAddr(request);
                        HistoryBean historyBean = new HistoryBean();
                        historyBean.setMessage("[" + userName + "]添加了新的印章");
                        historyBean.setType(Opt.GRXXGL_GRXXSZ_XZYZ);
                        historyBean.setOpUserId(user.getUserId());
                        historyBean.setIp(ip);
                        historyBean.setBopId(String.valueOf(user.getUserId()));
                        historyBean.setAddTime(TimeUtil.currentTimeMillis());
                        historyBean.setAddUser(String.valueOf(user.getUserId()));
                        historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                        historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                        //插入数据库
                        int ress = historyMapper.addHistory(historyBean);
                    }

                }
            }
            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("修改成功");

            //如果操作日志的开关已经打开
            if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                //添加修改了个人信息的操作记录
                // 先取得用户ip
                String ip = IpUtil.getIpAddr(request);
                HistoryBean historyBean = new HistoryBean();
                historyBean.setMessage("[" + userName + "]修改了个人信息");
                historyBean.setType(Opt.GRXXGL_GRXXSZ_XGGRXX);
                historyBean.setOpUserId(user.getUserId());
                historyBean.setIp(ip);
                historyBean.setBopId(String.valueOf(user.getUserId()));
                historyBean.setAddTime(TimeUtil.currentTimeMillis());
                historyBean.setAddUser(String.valueOf(user.getUserId()));
                historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                //插入数据库
                int ress = historyMapper.addHistory(historyBean);
            }


        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 修改手机号
     *
     * @param request
     * @param newPhone
     * @param oldPhone
     * @param code
     */
    public ResultMsg updatePhone(HttpServletRequest request, String newPhone, String oldPhone, String code) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.GRXXGL_SJHXG)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            if (null == newPhone || "".equals(newPhone) || null == oldPhone || "".equals(oldPhone) || null == code || "".equals(code)) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("非法操作");
                return ret;
            }

            User nUser = userMapper.getUserById(user.getUserId());
            if (!nUser.getPhone().equals(oldPhone)) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("旧手机号码不正确");
                return ret;
            }

            if (null == code || code.length() < 4) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("验证码不正确");
                return ret;
            }
            // 取得短信老数据
            List<BSms> oldDatas = mSmsMapper.getSmsByPhone(newPhone);
            if (oldDatas.size() >= 1 && code.equals(oldDatas.get(0).getCode()) && oldDatas.get(0).getFlg() != SmsController.IS_USED) {
                nUser.setPhone(newPhone);
                int res = userMapper.updateUserById(nUser);
                if (res > 0) {
                    ret.setCode(ResultMsg.SUCESS);
                    ret.setMsg("修改成功");

                    //如果操作日志的开关已经打开
                    if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                        //添加操作记录
                        // 先取得用户ip
                        String ip = IpUtil.getIpAddr(request);
                        HistoryBean historyBean = new HistoryBean();
                        historyBean.setMessage("[" + user.getUserName() + "]修改了手机号码，新手机为[" + newPhone + "]");
                        historyBean.setType(Opt.GRXXGL_GRXXSZ_XXSJH);
                        historyBean.setOpUserId(user.getUserId());
                        historyBean.setIp(ip);
                        historyBean.setBopId(String.valueOf(user.getUserId()));
                        historyBean.setAddTime(TimeUtil.currentTimeMillis());
                        historyBean.setAddUser(String.valueOf(user.getUserId()));
                        historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                        historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                        //插入数据库
                        int ress = historyMapper.addHistory(historyBean);
                    }

                } else {
                    ret.setCode(ResultMsg.ERROR);
                    ret.setMsg("修改失败，数据异常");
                    return ret;
                }
            } else {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("验证码不正确");
                return ret;
            }
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * 修改密码
     *
     * @param request
     * @param oldPassword
     * @param newPassword
     * @param newPassword2
     * @return
     */
    public ResultMsg updatePwd(HttpServletRequest request, String oldPassword, String newPassword, String newPassword2) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.GRXXGL_MMXG)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            if (null == oldPassword || "".equals(oldPassword)
                    || null == newPassword || "".equals(newPassword)
                    || null == newPassword2 || "".equals(newPassword2)
                    || !newPassword.equals(newPassword2)) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("非法操作");
                return ret;
            }

            User nUser = userMapper.getUserById(user.getUserId());
            if (!nUser.getPassword().equals(oldPassword)) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("旧密码错误");
                return ret;
            }

            // 必填字母数字特殊字符
            String reg = "^(?![0-9]+$)(?![^0-9]+$)(?![a-zA-Z]+$)(?![^a-zA-Z]+$)(?![a-zA-Z0-9]+$)[a-zA-Z0-9\\S]{6,}+$";
            if(!newPassword.matches(reg)){
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("密码要求长度至少6位，并且是字母加数字加特殊字符组合");
                return ret;
            }



            nUser.setPassword(newPassword);
            int res = userMapper.updateUserById(nUser);
            if (res > 0) {
                ret.setCode(ResultMsg.SUCESS);
                ret.setMsg("修改成功");
                //如果操作日志的开关已经打开
                if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                    //添加操作记录
                    // 先取得用户ip
                    String ip = IpUtil.getIpAddr(request);
                    HistoryBean historyBean = new HistoryBean();
                    historyBean.setMessage("[" + user.getUserName() + "]修改了密码");
                    historyBean.setType(Opt.GRXXGL_GRXXSZ_XXMM);
                    historyBean.setOpUserId(user.getUserId());
                    historyBean.setIp(ip);
                    historyBean.setBopId(String.valueOf(user.getUserId()));
                    historyBean.setAddTime(TimeUtil.currentTimeMillis());
                    historyBean.setAddUser(String.valueOf(user.getUserId()));
                    historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                    historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                    //插入数据库
                    int ress = historyMapper.addHistory(historyBean);
                }

            } else {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("修改失败，数据异常");
                return ret;
            }


        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 分页获取我的印章列表
     *
     * @param request
     * @param page
     * @param size
     * @return
     */
    public ResultMsg getMysealPage(HttpServletRequest request, Integer page, Integer size) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否有客户信息一览的权限
//            if (!CheckTool.checkAuthority(user, AuthorityID.GRXXGL_GRQZGL)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }
            if (page != null && size != null) {
                page = (page - 1) * size;
            }

            User nUser = userMapper.getUserByIdOrS(user.getUserId());

            //分页查询数据
            List<SealBean> datas = sealMapper.getMysealPage(page, size, user.getUserId());
            // 总条数
            long total = sealMapper.getTotalNumber(user.getUserId());

            MySealBean mySealBean = new MySealBean();
            mySealBean.setSealBeans(datas);
            mySealBean.setNowSealId(nUser.getSealId());
            List<MySealBean> mySealBeans = new ArrayList<MySealBean>();
            mySealBeans.add(mySealBean);

            RespPageBean bean = new RespPageBean();
            bean.setData(mySealBeans);
            bean.setTotal(total);
            ret.setCode(ResultMsg.SUCESS);
            ret.setData(bean);
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * 新建一个我的印章图片
     *
     * @param request
     * @param userId
     * @param imgstr
     * @return
     */
    public ResultMsg addMysealPage(HttpServletRequest request, String userId, String imgstr) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否有客户信息一览的权限
//            if (!CheckTool.checkAuthority(user, AuthorityID.GRXXGL_GRQZGL)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            if("".equals(imgstr)){
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("非法操作");
                return ret;
            }
            String [] qiangzArr =imgstr.split(",");
            long ntiem =TimeUtil.currentTimeMillis();
            String temporaryName=userId+ntiem+".png";
            String localPath = Config.UPLOADFOLDER + "/image/"+temporaryName;

           boolean mres = PNGUtil.markImageByText(qiangzArr[1],localPath);
           //生生带水印的印章成功
           if(mres){
               //读取带水印的印章
               String yzBase64 =  PNGUtil.TuImage(localPath);
               if(!"".equals(yzBase64)){
                   User nUser = userMapper.getUserByIdOrS(user.getUserId()); // 取得用户信息
                   SealBean sealBean = new SealBean();
                   sealBean.setSealUrl(imgstr); // 设置图片数据
                   sealBean.setSealUrlWmk(qiangzArr[0]+","+yzBase64);
                   sealBean.setUserId(nUser.getUserId()); // 设置用户id
                   sealBean.setAddTime(TimeUtil.currentTimeMillis());
                   sealBean.setSealUrlPath("/image/" + temporaryName);
                   sealMapper.addSeal(sealBean); // 插入数据库
                   ret.setCode(ResultMsg.SUCESS);
                   ret.setMsg("数据插入成功");
                   //删除文件
                  // File file = new File(temporaryName);
                  // file.delete();
               }else{
                   ret.setCode(ResultMsg.SUCESS);
                   ret.setMsg("保存印章失败，请稍后在试");
               }
           }else {
               ret.setCode(ResultMsg.SUCESS);
               ret.setMsg("保存印章失败，请稍后在试");
           }




        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }




    /**
     * 设置印章的启用禁用状态
     *
     * @param request
     * @param sealId  0代表禁用
     * @return
     */
    public ResultMsg setSealType(HttpServletRequest request, long sealId) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否有客户信息一览的权限
//            if (!CheckTool.checkAuthority(user, AuthorityID.GRXXGL_GRQZGL)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }
            User nUser = userMapper.getUserById(user.getUserId());
            nUser.setSealId(sealId);
            int res = userMapper.updateUserById(nUser);
            if (res > 0) {
                ret.setCode(ResultMsg.SUCESS);
                ret.setMsg("修改成功");
                //如果操作日志的开关已经打开
                if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                    //添加操作记录
                    // 先取得用户ip
                    String ip = IpUtil.getIpAddr(request);
                    HistoryBean historyBean = new HistoryBean();
                    if (sealId == 0) {
                        historyBean.setMessage("[" + user.getUserName() + "]停用了了印章");
                        historyBean.setType(Opt.GRXXGL_GRXXSZ_JYYZ);
                    } else {
                        historyBean.setMessage("[" + user.getUserName() + "]启用了了印章");
                        historyBean.setType(Opt.GRXXGL_GRXXSZ_QYYZ);
                    }
                    historyBean.setOpUserId(user.getUserId());
                    historyBean.setIp(ip);
                    historyBean.setBopId(String.valueOf(user.getUserId()));
                    historyBean.setAddTime(TimeUtil.currentTimeMillis());
                    historyBean.setAddUser(String.valueOf(user.getUserId()));
                    historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                    historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                    //插入数据库
                    int ress = historyMapper.addHistory(historyBean);
                }

            } else {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("修改失败，数据异常");
                return ret;
            }


        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }




    /**
     * 设置印章的启用禁用状态
     *
     * @param request
     * @param sealId  0代表禁用
     * @return
     */
    public ResultMsg deleteSeal(HttpServletRequest request, long sealId) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否有客户信息一览的权限
//            if (!CheckTool.checkAuthority(user, AuthorityID.GRXXGL_GRQZGL)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            long res = sealMapper.deleteSeal(sealId);
            if (res > 0) {
                ret.setCode(ResultMsg.SUCESS);
                ret.setMsg("操作成功");


            } else {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("修改失败，数据异常");
                return ret;
            }


        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * 新增用户
     *
     * @param request
     * @param userName
     * @param phone
     * @param account
     * @param department
     * @param role
     * @param password
     * @param password2
     * @return
     */
    public ResultMsg addUser(HttpServletRequest request, String userName, String phone, String account,
                             String department, String role, String password, String password2) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否有客户信息一览的权限
//            if (!CheckTool.checkAuthority(user, AuthorityID.YHGL_XZYH)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            //参数判断
            if (null == userName || "".equals(userName) || userName.length() > 30 ||
                    null == phone || "".equals(phone) || !RegularUtil.isMobile(phone) ||
                    null == account || "".equals(account) || account.length() > 16 || department.length() > 32 ||
                    null == password || "".equals(password) || !password.equals(password2) || "".equals(role)) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("非法操作");
                return ret;
            }


            // 必填字母数字特殊字符
           // String reg = "^(?![A-Za-z0-9]+$)(?![a-z0-9\\W]+$)(?![A-Za-z\\W]+$)(?![A-Z0-9\\W]+$)[a-zA-Z0-9\\W]{8,}$";

            //密码必须是包含大写字母、小写字母、数字、特殊符号（不是字母，数字，下划线，汉字的字符）的6位以上组合
            String reg = "^(?![A-Za-z0-9]+$)(?![a-z0-9\\W]+$)(?![A-Za-z\\W]+$)(?![A-Z0-9\\W]+$)[a-zA-Z0-9\\W]{6,}$";

            if(password.matches(reg)){
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("密码要求长度至少6位");
                return ret;
            }

            //判断账号重复
            long mcount1 =   userMapper.getUserByCount(account);
            if(mcount1>0){
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("该账号已经被注册");
                return ret;
            }

            //判断账号重复
            long mcount2 =  userMapper.getUserByPhoneCun(phone);
            if(mcount2>0){
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("该手机号已经被注册");
                return ret;
            }

            //添加新用户
            User asUser = new User();
            asUser.setPhone(phone);
            asUser.setAccount(account);
            asUser.setRole(role);
            asUser.setPassword(password);
            asUser.setDepartment(department);
            asUser.setUserName(userName);
            asUser.setStatue(1);

            long mtime = TimeUtil.currentTimeMillis();
            asUser.setAddTime(mtime);
            asUser.setAddUser(String.valueOf(user.getUserId()));
            asUser.setUpdateTime(mtime);
            asUser.setUpdateUser(String.valueOf(user.getUserId()));
            asUser.setSysStatus(1);


            int res = userMapper.createUser(asUser);
            if (res > 0) {
                ret.setCode(ResultMsg.SUCESS);
                ret.setMsg("添加成功");
                //如果操作日志的开关已经打开
                if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                    //添加操作记录
                    // 先取得用户ip
                    String ip = IpUtil.getIpAddr(request);
                    HistoryBean historyBean = new HistoryBean();
                    historyBean.setMessage("[" + user.getUserName() + "] 新增了用户： [" + userName + "]");
                    historyBean.setType(Opt.YHGL_XZYH_XZYH);
                    historyBean.setOpUserId(user.getUserId());
                    historyBean.setIp(ip);
                    historyBean.setBopId(String.valueOf(asUser.getUserId()));
                    historyBean.setAddTime(TimeUtil.currentTimeMillis());
                    historyBean.setAddUser(String.valueOf(user.getUserId()));
                    historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                    historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                    //插入数据库
                    int ress = historyMapper.addHistory(historyBean);
                }


            } else {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("数据异常");
                return ret;
            }
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;

    }


    /**
     * 修改用户
     *
     * @param request
     * @param userName
     * @param phone
     * @param account
     * @param department
     * @param role
     * @return
     */
    public ResultMsg updateUserYl(HttpServletRequest request, long userId, String userName, String phone, String account,
                                  String department, String role) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否有客户信息一览的权限
//            if (!CheckTool.checkAuthority(user, AuthorityID.YHGL_XZYH)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }






            //参数判断
            if (userId == 0 || null == userName || "".equals(userName) || userName.length() > 30 ||
                    null == phone || "".equals(phone) || !RegularUtil.isMobile(phone) ||
                    null == account || "".equals(account) || account.length() > 16 || department.length() > 32 ||
                    "".equals(role)) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("非法操作");
                return ret;
            }
            User asUser = userMapper.getUserById(userId);

            if(!asUser.getAccount().equals(account)){
                //判断账号重复
                long mcount1 =   userMapper.getUserByCount(account);
                if(mcount1>0){
                    ret.setCode(ResultMsg.ERROR);
                    ret.setMsg("该账号已经被注册");
                    return ret;
                }
            }

            if(!asUser.getPhone().equals(phone)){
                //判断账号重复
                long mcount2 =  userMapper.getUserByPhoneCun(phone);
                if(mcount2>0){
                    ret.setCode(ResultMsg.ERROR);
                    ret.setMsg("该手机号已经被注册");
                    return ret;
                }
            }




            asUser.setPhone(phone);
            asUser.setAccount(account);
            asUser.setRole(role);
            asUser.setDepartment(department);
            asUser.setUserName(userName);
            long mtime = TimeUtil.currentTimeMillis();
            asUser.setUpdateTime(mtime);
            asUser.setUpdateUser(String.valueOf(user.getUserId()));

            int res = userMapper.updateUser(asUser);
            if (res > 0) {
                ret.setCode(ResultMsg.SUCESS);
                ret.setMsg("修改成功");
                //如果操作日志的开关已经打开
                if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                    //添加操作记录
                    // 先取得用户ip
                    String ip = IpUtil.getIpAddr(request);
                    HistoryBean historyBean = new HistoryBean();
                    historyBean.setMessage("[" + user.getUserName() + "] 修改了用户： [" + userName + "]");
                    historyBean.setType(Opt.YHGL_YHYL_XGYH);
                    historyBean.setOpUserId(user.getUserId());
                    historyBean.setIp(ip);
                    historyBean.setBopId(String.valueOf(asUser.getUserId()));
                    historyBean.setAddTime(TimeUtil.currentTimeMillis());
                    historyBean.setAddUser(String.valueOf(user.getUserId()));
                    historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                    historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                    //插入数据库
                    int ress = historyMapper.addHistory(historyBean);
                }


            } else {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("数据异常");
                return ret;
            }
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;

    }


    /**
     * 分页查询用户列表
     *
     * @param request
     * @param page
     * @param size
     * @param userName
     * @param phone
     * @param account
     * @param role
     * @param statue
     * @return
     */
    public ResultMsg getUserListPage(HttpServletRequest request, Integer page, Integer size, String userName,
                                     String phone, String account, int role, int statue) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否有客户信息一览的权限
//            if (!CheckTool.checkAuthority(user, AuthorityID.YHGL_YHCX)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            if (page != null && size != null) {
                page = (page - 1) * size;
            }
            List<User> datas = userMapper.getUserListPage(page, size, userName, phone, account, role, statue);
            long total = userMapper.getTotalNumber(userName, phone, account, role, statue);
            RespPageBean bean = new RespPageBean();
            bean.setData(datas);
            bean.setTotal(total);
            ret.setCode(ResultMsg.SUCESS);
            ret.setData(bean);


        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 重置密码
     *
     * @param request
     * @return
     */
    public ResultMsg resetPassword(HttpServletRequest request, long userId, String msd, String userName) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否有客户信息一览的权限
//            if (!CheckTool.checkAuthority(user, AuthorityID.YHGL_YHCX)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }
            long res = userMapper.resetPassword(userId, msd);
            if (res > 0) {
                ret.setCode(ResultMsg.SUCESS);
                ret.setMsg("操作成功");
                //如果操作日志的开关已经打开
                if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                    //添加操作记录
                    // 先取得用户ip
                    String ip = IpUtil.getIpAddr(request);
                    HistoryBean historyBean = new HistoryBean();
                    historyBean.setMessage("[" + user.getUserName() + "] 重置了 [" + userName + " ] 的密码");
                    historyBean.setType(Opt.YHGL_YHYL_CZMM);
                    historyBean.setOpUserId(user.getUserId());
                    historyBean.setIp(ip);
                    historyBean.setBopId(String.valueOf(userId));
                    historyBean.setAddTime(TimeUtil.currentTimeMillis());
                    historyBean.setAddUser(String.valueOf(user.getUserId()));
                    historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                    historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                    //插入数据库
                    historyMapper.addHistory(historyBean);
                }

            } else {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("数据异常");
            }
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 用户管理  禁止登陆 允许登陆
     *
     * @param request
     * @param userId
     * @param statue
     * @param userName
     * @return
     */
    public ResultMsg loginYhglRes(HttpServletRequest request, long userId, int statue, String userName) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否有客户信息一览的权限
//            if (!CheckTool.checkAuthority(user, AuthorityID.YHGL_YHCX)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }
            int res = userMapper.updateStatueByUserId(userId, statue);
            if (res > 0) {
                ret.setCode(ResultMsg.SUCESS);
                ret.setMsg("操作成功");
                //如果操作日志的开关已经打开
                if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                    //添加操作记录
                    // 先取得用户ip
                    String ip = IpUtil.getIpAddr(request);
                    HistoryBean historyBean = new HistoryBean();

                    if (statue == 2) {
                        historyBean.setMessage("[" + user.getUserName() + "] 禁止了： [" + userName + "] 登陆");
                        historyBean.setType(Opt.YHGL_YHYL_JZDL);
                    } else {
                        historyBean.setMessage("[" + user.getUserName() + "] 允许了： [" + userName + "] 登陆");
                        historyBean.setType(Opt.YHGL_YHYL_YXDL);
                    }
                    historyBean.setOpUserId(user.getUserId());
                    historyBean.setIp(ip);
                    historyBean.setBopId(String.valueOf(userId));
                    historyBean.setAddTime(TimeUtil.currentTimeMillis());
                    historyBean.setAddUser(String.valueOf(user.getUserId()));
                    historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                    historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                    //插入数据库
                    int ress = historyMapper.addHistory(historyBean);
                }

            } else {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("数据异常");
            }
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }



    /**
     * 查询 维修员和检验员  lifubo(new)
     * @param request
     * @return
     */
    public ResultMsg getUserByRoleWxOrJyy(HttpServletRequest request){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            List<User>  data = new ArrayList<>();
            List<User>  alldata = userMapper.getUserListJc();
            for(User user:alldata){
                String jsStr = user.getRole();
                String [] jsArray =jsStr.split(",");
                List<String> listB= Arrays.asList(jsArray);
                if(listB.contains("5") || listB.contains("7")){
                    data.add(user);
                }
            }
            ret.setCode(ResultMsg.SUCESS);
            ret.setData(data);

        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }



    /**
     * 查询某个角色的所有用户 lifubo(new)
     *
     * @param request
     * @param role
     * @return
     */
    public ResultMsg getUserByRoleExceptMe(HttpServletRequest request, String role) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            // 权限检查
            User user = UserInfoUtil.getUser_Web(request);
            ret = new ResultMsg(); // 声明一个返回值
            List<User>  data = new ArrayList<>();
            List<User>  alldata = userMapper.getUserByRoleExceptMe(user.getUserId());
            for(User user2:alldata){
                String jsStr = user2.getRole();
                String [] jsArray =jsStr.split(",");
                List<String> listB= Arrays.asList(jsArray);
                if(listB.contains(role)){
                    data.add(user2);
                }
            }
            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("查询成功");
            ret.setData(data);
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }





    /**
     * 查询某个角色的所有用户  lifubo(new)
     *
     * @param request
     * @param role
     * @return
     */
    public ResultMsg getUserByRole2(HttpServletRequest request, String role) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            List<User>  data = new ArrayList<>();
            List<User>  alldata = userMapper.getUserList2();
            for(User user:alldata){
                String jsStr = user.getRole();
                String [] jsArray =jsStr.split(",");
                List<String> listB= Arrays.asList(jsArray);
                if(listB.contains(role)){
                    data.add(user);
                }
            }
            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("查询成功");
            ret.setData(data);
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }




    /**
     * 查询所有用户
     *
     * @param request
     * @return
     */
    public ResultMsg getUserList(HttpServletRequest request) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            //查询所有用户
            List<User> data = userMapper.getUserList();
            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("查询成功");
            ret.setData(data);
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * 查询某个角色的用户 包含印章信息   lifubo(new)
     *
     * @param request
     * @return
     */
    public ResultMsg getUserListJc(HttpServletRequest request, String role) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 首先取得用户信息
            //User user = UserInfoUtil.getUser_Web(request);
            List<User>  data = new ArrayList<>();
            List<User>  alldata = userMapper.getUserListJc();
            for(User user:alldata){
                //base64图片加水印
                String jsStr = user.getRole();
                String [] jsArray =jsStr.split(",");
                List<String> listB= Arrays.asList(jsArray);
                if(listB.contains(role)){
                    data.add(user);
                }
            }
            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("查询成功");
            ret.setData(data);
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }



    /**
     * 查询某个角色的用户 包含印章信息   lifubo(new)
     *
     * @param request
     * @return
     */
    public ResultMsg getUserListJcLHQ(HttpServletRequest request, String role) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 首先取得用户信息
            //User user = UserInfoUtil.getUser_Web(request);
            List<User>  alldata = userMapper.getUserListJc();
            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("查询成功");
            ret.setData(alldata);
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }



}
